package cn.aion.crawlers;

import cn.aion.dao.ProjectVideoDAO;
import cn.aion.dao.VideoDataDAO;
import cn.aion.model.BilibiliVideo;
import cn.aion.model.ProjectVideo;
import cn.aion.model.VideoData;
import cn.aion.util.Helper;
import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.def.BaseSeimiCrawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * B站扫描规则：http://www.bilibili.com/video/av7377237/
 * Created by Aion on 2016/11/2.
 */
@Crawler(name = "bilibili", useUnrepeated = false)
public class Bilibili extends BaseSeimiCrawler {
    @Autowired
    private ProjectVideoDAO projectVideoDAO;
    @Autowired
    private VideoDataDAO videoDataDAO;

    @Value("${seimiAgentHost}")
    private String seimiAgentHost;
    @Value("${seimiAgentPort}")
    private int seimiAgentPort;
    @Override
    public String seimiAgentHost() { return this.seimiAgentHost; }
    @Override
    public int seimiAgentPort() { return this.seimiAgentPort; }

    @Override
    public String[] startUrls() {
        return new String[]{"http://www.van-cool.com/admin/base/scan"};
    }

    @Override
    public void start(Response response) {
        main();
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void main() {
        logger.info("开启B站扫描任务");
        try {
            List<ProjectVideo> list = projectVideoDAO.getVideoAll();
            for (ProjectVideo video : list) {
                String url = video.getBilibiliUrl();
                if (url != null && !url.isEmpty()) {
                    logger.info("扫描地址：{}", url);
                    push(Request.build(url, "fetchId"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchId(Response response) {
        try {
            String url = response.getRealUrl();
            String [] arr = url.split("/");
            String dataUrl = "http://api.bilibili.com/archive_stat/stat?aid="+arr[4].replace("av","");
            push(Request.build(dataUrl, "fetchData"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void fetchData(Response response){
        JXDocument doc = response.document();

        String tvInfo = response.getContent();
        BilibiliVideo bilibiliVideo = JSON.parseObject(tvInfo, cn.aion.model.BilibiliVideo.class);
        // 根据URL获取视频ID
        String videoId = response.getRealUrl().substring(response.getRealUrl().indexOf("=")+1);
        ProjectVideo projectVideo = projectVideoDAO.selectOneByBilibili(videoId);
        if (projectVideo != null) {
            logger.info("{} | 播放总数:{}", projectVideo.getTitle(), bilibiliVideo.getData().getView());

            Integer playCount = bilibiliVideo.getData().getView();
            // 计算当日的递增数量
            VideoData preData = videoDataDAO.selectOnePrevious(projectVideo.getId(), 5);
            Integer addCount = playCount;
            if (preData != null) {
                addCount = playCount - preData.getPlayCount();
            }

            // 如果当天已经抓取过数据就更新数据
            VideoData videoData = videoDataDAO.selectOneToday(projectVideo.getId(), 5);
            if (videoData != null) {
                if (playCount != 0) {
                    videoData.setPlayCount(playCount);
                    videoData.setPlayAdd(addCount);
                    videoDataDAO.update(videoData);
                }
            } else {
                VideoData newData = new VideoData();
                newData.setPlayCount(playCount);
                newData.setPlayAdd(addCount);
                newData.setVideoId(projectVideo.getId());
                newData.setSrcType(5);
                videoDataDAO.save(newData);
            }
            // 更新总数据
            if (playCount != 0) {
                projectVideoDAO.updateBilibiliVideoCount(projectVideo.getId(), playCount);
                projectVideoDAO.updateTotal(projectVideo.getId());
                projectVideoDAO.updateApplyTotal(projectVideo.getProjectId(), projectVideo.getAnchorId(), Helper.getVideoTotal(projectVideo));
            }
        }

    }

}
